<template>
  <div class="procure-turnover">
    <header>
      <h3>商品库存流水记录明细</h3>
      <el-input v-model="searchkey" style="width: 280px" placeholder="请输入商品/ID/SKU编码" :prefix-icon="Search" />
    </header>

    <!-- 搜索表单 -->
    <div class="center-search-wrap">
      <div>
        <SearchForm ref="searchFormRef" :list="[...formList]" colBtn @submit="search" @reset="reset"></SearchForm>
      </div>
    </div>

    <div class="download-btn">
      <el-button type="primary" :loading="downloading" @click="downloadExcel">导出</el-button>
    </div>

    <!-- 表单数据 -->
    <!-- <el-table class="jzt-table mt20" :data="list" border stripe style="width: 100%">
      <el-table-column fixed prop="date" show-overflow-tooltip label="商品信息" width="405">
        <template #default="scope">
          <div class="info">
            <div class="left">
              <img :src="scope.row.mainPicUrl" alt="" />
            </div>
            <div class="right">
              <h3 class="name" style="white-space: break-spaces; word-break: break-all">
                {{ scope.row.productAliasName || "-" }}
              </h3>
              <p style="white-space: break-spaces; word-break: break-all">{{ scope.row.skuSpecification }}</p>
              <p>SKU编码：{{ scope.row.skuCode || "-" }}</p>
              <p>ID：{{ scope.row.productId || "-" }}</p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="preview" show-overflow-tooltip label="商品分类" width="100" />
      <el-table-column prop="warehouseName" show-overflow-tooltip label="仓库" />
      <el-table-column prop="customerName" show-overflow-tooltip label="关联客户" width="180">
        <template #default="scope">
          <span>{{
            scope.row.customerName || scope.row.customerMobileCode
              ? scope.row.customerName + "-" + scope.row.customerMobileCode
              : "-"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="productUnit" show-overflow-tooltip label="单位" width="100">
        <template #default="scope">
          {{ getName(scope.row.productUnit) }}
        </template>
      </el-table-column>
      <el-table-column prop="outProductNum" show-overflow-tooltip label="出库数量" width="180" />
      <el-table-column prop="outProductPartNum" show-overflow-tooltip label="出库件数" width="180" />
      <el-table-column prop="inProductNum" show-overflow-tooltip label="入库数量" width="180" />
      <el-table-column prop="inProductPartNum" show-overflow-tooltip label="入库件数" width="180" />
      <el-table-column prop="unitName" show-overflow-tooltip label="往来单位" width="180">
        <template #default="scope">
          <span>{{ scope.row.unitName || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="changeType" show-overflow-tooltip label="变动类型" width="180">
        <template #default="scope">
          {{ getTypeName(scope.row.changeType) }}
        </template>
      </el-table-column>
      <el-table-column prop="linkCode" show-overflow-tooltip label="关联编码" width="180" />
      <el-table-column prop="createTime" show-overflow-tooltip label="变动时间" width="180" />
      <el-table-column prop="remark" show-overflow-tooltip label="商品备注" width="240">
        <template #default="scope">
          <RemarkEditor v-model="scope.row.remark" :isEdit="false" />
        </template>
      </el-table-column>
    </el-table> -->
    <div class="products-list mt20" style="overflow-x: auto">
      <div class="my-table" style="min-width: 2700px">
        <div class="table-header">
          <div>
            <div>
              <div class="col1">商品信息</div>
              <div class="col2">商品分类</div>
              <div class="col3">仓库</div>
              <div class="col4">关联客户</div>
              <div class="col5">单位</div>
              <div class="col6">出库数量</div>
              <div class="col6">出库件数</div>
              <div class="col6">入库数量</div>
              <div class="col6">入库件数</div>
              <div class="col6">往来单位</div>
              <div class="col6">变动类型</div>
              <div class="col7">订单备注</div>
              <div class="col6">关联编码</div>
              <div class="col6">变动时间</div>
            </div>
          </div>
        </div>

        <div class="table-body" v-if="list.length > 0">
          <div class="list-item" v-for="(item, index) in list" :key="index">
            <div>
              <div class="col1">
                <div>
                  <div class="left">
                    <img :src="item.mainPicUrl" alt="" />
                  </div>
                  <div class="right">
                    <h3 class="name text-break">{{ item.productAliasName || "-" }}</h3>
                    <p class="text-break">
                      {{ item.skuSpecification || "-" }}
                    </p>
                    <p class="text-break">SKU编码：{{ item.skuCode || "-" }}</p>
                    <p>ID:{{ item.productId || "-" }}</p>
                  </div>
                </div>
              </div>
              <div class="col2">{{ item.preview || "-" }}</div>
              <div class="col3">{{ item.warehouseName || "-" }}</div>
              <div class="col4">
                <span>{{
                  item.customerName || item.customerMobileCode ? item.customerName + "-" + item.customerMobileCode : "-"
                }}</span>
              </div>
              <div class="col5">{{ getName(item.productUnit) }}</div>
              <div class="col6">{{ item.outProductNum || "-" }}</div>
              <div class="col6">{{ item.outProductPartNum || "-" }}</div>
              <div class="col6">{{ item.inProductNum || "-" }}</div>
              <div class="col6">{{ item.inProductPartNum || "-" }}</div>
              <div class="col6">{{ item.unitName || "-" }}</div>
              <div class="col6">{{ getTypeName(item.changeType) }}</div>
              <div class="col7">
                <RemarkEditor v-model="item.orderRemark" :isEdit="false" />
              </div>
              <div class="col6">{{ item.linkCode || "-" }}</div>
              <div class="col6">{{ item.createTime || "-" }}</div>
            </div>
            <div class="tips">
              <p class="label">商品备注：</p>
              <!-- <el-input maxlength="200" v-model="item.remark" placeholder="请输入"></el-input> -->
              <RemarkEditor v-model="item.remark" :isEdit="false" />
            </div>
          </div>
        </div>
        <div v-else style="display: flex; justify-content: center; width: 100%">
          <el-empty description="暂无数据" />
        </div>
      </div>
    </div>

    <div class="pt20 pb20" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.sizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import SearchForm from "@/components/SearchForm";
import useCodeArrStore from "@/store/modules/select";
import { ListPage } from "@/apis/procure/warehouse";
import { getcategoryList2 } from "@/apis/products/specifications";
import { getLogsList, getcategoryList, download } from "@/apis/procure/inventory-turnover";
import { useRoute } from "vue-router";
const route = useRoute();
import { findAncestorsById } from "@/utils";
import RemarkEditor from "@/components/RemarkEditor";

const searchkey = ref("");
const formData = ref({});
const searchFormRef = ref();
const formList = ref([
  {
    label: "仓库",
    model: "warehouseId",
    type: "select",
    labelWidth: "70",
    data: [],
    props: { label: "warehouseName", value: "warehouseId" }
  },
  {
    label: "客户信息",
    model: "customerType-customerSearch",
    type: "select-input",
    labelWidth: "70",
    data: [
      // {
      //   value: 0,
      //   label: "全部"
      // },
      {
        value: 1,
        label: "姓名"
      },
      {
        value: 2,
        label: "电话"
      }
    ]
  },
  {
    label: "变动类型",
    model: "changeType-linkCode",
    type: "select-input",
    labelWidth: "70",
    placeholder: "请输入关联编码",
    data: [
      {
        value: 1,
        label: "其他出库"
      },
      {
        value: 2,
        label: "订单出库"
      },
      {
        value: 3,
        label: "销售退货"
      },
      {
        value: 4,
        label: "采购入库"
      },
      {
        value: 5,
        label: "采购退货"
      },
      {
        value: 6,
        label: "调拨出库"
      },
      {
        value: 7,
        label: "调拨入库"
      },
      {
        value: 8,
        label: "其他入库"
      }
    ]
  },
  {
    label: "变动时间",
    model: "changeTime",
    type: "daterange",
    labelWidth: "70"
  },
  {
    label: "商品分类",
    model: "categoryIds",
    type: "cascader",
    labelWidth: "70",
    data: [],
    props: { checkStrictly: false, expandTrigger: "hover", label: "name", value: "categoryId", multiple: true }
  }
]);
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const optionInfo = ref({ isShow: false });
const currObj = ref({});

onMounted(async () => {
  const res = await ListPage({ page: 1, size: 9999 }); //仓库list
  const res2 = await getcategoryList({ searchkey: "" }); //商品分类
  formList.value.map(item => {
    if (item.model === "warehouseId") {
      item.data = res.data.records;
    } else if (item.model === "categoryIds") {
      item.data = res2.data;
    }
  });

  // 如果地址栏有参数（从库存管理的操作栏点击流水按钮跳转过来）
  if (route.query.skuCode) {
    //回显搜索关键词skuCode
    searchkey.value = route.query.skuCode;

    // //回显仓库
    // formData.value.warehouseId = "1811388159391481856";
    // searchFormRef.value.setFormData("warehouseId", "1811388159391481856");

    // //回显商品分类
    // const arr = findAncestorsById("1791362204937289728", res2.data, "categoryId");
    // const _categoryIds = [arr[arr.length - 1].fomart?.split("-")];
    // formData.value.categoryIds = _categoryIds;
    // searchFormRef.value.setFormData("categoryIds", _categoryIds);
  }
  getList();
});

const getTypeName = val => {
  const arr = [
    { label: "其他出库", value: 1 },
    { label: "订单出库", value: 2 },
    { label: "销售退货", value: 3 },
    { label: "采购入库", value: 4 },
    { label: "采购退货", value: 5 },
    { label: "调拨出库", value: 6 },
    { label: "调拨入库", value: 7 },
    { label: "其他入库", value: 8 }
  ];
  const obj = arr.find(item => item.value === val);
  return obj?.label;
};

//关闭库存分布弹窗
const close = () => {
  optionInfo.value.isShow = false;
};

const getList = () => {
  getLogsList({
    ...formData.value,
    categoryIds: formData.value?.categoryIds ? formData.value.categoryIds.map(item => item[item.length - 1]) : [],
    productSearch: searchkey.value,
    page: pagination.value.page,
    size: pagination.value.size
  }).then(res => {
    if (res.code === 200) {
      list.value = res.data.records;
      pagination.value.total = res.data.total;
    }
  });
};

// 表单查询组件submit回调
const search = form => {
  console.log("查询表单数据===", form);
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    _form.startDate = _form.changeTime ? _form.changeTime[0] : "";
    _form.endDate = _form.changeTime ? _form.changeTime[1] : "";
    delete _form?.changeTime;
    formData.value = _form;
  } else {
    formData.value = {};
  }
  nextTick(() => {
    getList();
  });
};
//清空查询表单
const reset = () => {
  search("");
};

//单位转换
const getName = code => {
  return useCodeArrStore().getDictName("shop_unit", code);
};

//拼接商品的sku规格
const getSpes = properties => {
  if (!properties) return "-";
  const arr = JSON.parse(properties) || [];
  if (arr.length > 1) {
    const str = arr.reduce((a, b) => {
      return a.specificationVal + "+" + b.specificationVal;
    });
    return str;
  } else if (arr.length === 1) {
    return arr[0].specificationVal;
  } else {
    return "-";
  }
};
const handleSizeChange = val => {
  pagination.value.size = val;
  getList();
};
const handleCurrentChange = val => {
  pagination.value.page = val;
  getList();
};

// 导出
const downloading = ref(false);
const downloadExcel = async () => {
  let formData = JSON.parse(JSON.stringify(searchFormRef.value.getFormData()));
  formData.startDate = formData.changeTime ? formData.changeTime[0] : "";
  formData.endDate = formData.changeTime ? formData.changeTime[1] : "";
  delete formData?.changeTime;
  downloading.value = true;
  const res = await download({
    ...formData,
    categoryIds: formData?.categoryIds ? formData.categoryIds.map(item => item[item.length - 1]) : [],
    productSearch: searchkey.value
  });
  downloading.value = false;
  let url = window.URL.createObjectURL(res);
  const a = document.createElement("a");
  a.href = url;
  a.download = "库存流水.xlsx";
  a.click();
  URL.revokeObjectURL(url);
};
</script>

<style lang="scss" scoped>
.info {
  display: flex;
  .left {
    img {
      width: 80px;
      height: 80px;
      border-radius: 4px;
    }
  }
  .right {
    padding-left: 18px;
    .name {
      font-size: 14px;
      color: #3d3d3d;
      margin-bottom: 5px;
    }
    p {
      font-size: 12px;
      color: #86909c;
      margin-bottom: 5px;
    }
  }
}
.procure-turnover {
  padding: 0 20px;
  height: calc(100% - 0px);
  overflow-y: auto;
  & > header {
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e2e8f0;
    position: sticky;
    top: 0;
    z-index: 22;
    background-color: white;
    margin: 0 -20px;
    border-radius: 10px;
    h3 {
      font-size: 18px;
      font-weight: normal;
      position: relative;
      padding-left: 14px;
      &::before {
        position: absolute;
        content: "";
        width: 6px;
        height: 6px;
        border-radius: 50%;
        top: 8px;
        left: 0;
        background-color: #409eff;
      }
    }
  }
  .center-search-wrap {
    background-color: #f6f8fa;
    padding: 0 20px 0 20px;
    margin-top: 20px;
    :deep(.el-input-group__append) {
      padding: 0 !important;
    }
    & > div {
      // display: flex;
      // justify-content: space-between;
      padding: 20px 0 2px 0;
    }
    :deep(.el-form) {
      flex: 1;
    }
    .btn-wrap {
      width: 80px;
    }
  }
  .download-btn {
    margin-top: 20px;
  }
}
.products-list {
  .table-header {
    background-color: #f2f6fc;
    margin-bottom: 10px;
  }
  .table-body {
    max-height: calc(100vh - 505px);
    // overflow: auto;
    .list-item {
      margin-bottom: 10px;
      & > div {
        border: 1px solid #e1e6ed;
        display: flex;
        &:not(:first-of-type) {
          border-left: none;
        }
        &:not(:last-of-type) {
          & > div:not(:last-of-type) {
            border-right: 1px solid #e1e6ed;
          }
        }
        & > div {
          display: flex;
          align-items: center;
        }
      }
      .col1 {
        min-width: 360px;
        & > div {
          display: flex;
        }

        .left {
          img {
            width: 80px;
            height: 80px;
            border-radius: 4px;
          }
        }
        .right {
          padding-left: 18px;
          .name {
            font-size: 14px;
            color: #3d3d3d;
            margin-bottom: 5px;
          }
          p {
            font-size: 12px;
            color: #86909c;
            margin-bottom: 5px;
          }
        }
      }
      .tips {
        display: flex;
        padding: 16px 14px;
        border-top: none;
        border-left: 1px solid #e1e6ed !important;
        p.label {
          width: 72px;
        }
        .el-input {
          flex: 1;
          .el-input__wrapper {
            background-color: #f2f3f5;
          }
        }
      }
    }
  }
  .table-header,
  .table-body {
    & > div > div:first-of-type {
      display: flex;
      justify-content: space-between;
      & > div {
        padding: 14px 20px;
        &.col1 {
          // width: 45%;
          flex: 1;
          min-width: 360px;
        }
        &.col4,
        &.col5,
        &.col2,
        &.col3 {
          width: 140px;
          box-sizing: border-box;
        }
        &.col6 {
          width: 180px;
          box-sizing: border-box;
        }
        &.col7 {
          width: 260px;
          box-sizing: border-box;
        }
      }
    }
  }
}
</style>
